﻿using AntaresShell.BaseClasses;
using AntaresShell.Common;
using AntaresShell.Common.MessageTemplates;
using Repository.MODELs;
using System.Linq;
using Repository.Repositories;
using System.Collections.ObjectModel;
using Repository.Sync;

namespace Antares.VIEWMODELs
{
    public class ProjectOverviewViewModel : ViewModelBase
    {
        private ObservableCollection<ProjectInformationModel> _projects;

        public ObservableCollection<ProjectInformationModel> Projects
        {
            get { return _projects; }
            set { SetProperty(ref _projects, value); }
        }

        public ProjectOverviewViewModel()
        {
            Messenger.Instance.Register<Refresh>(RefreshAll);
            BindingData();
            Messenger.Instance.Register<DeleteProjectMsg>(DeleteProjects);
        }

        private void RefreshAll(object obj)
        {
            BindingData();
        }

        private async void DeleteProjects(object args)
        {
            Projects = await ProjectRepository.Instance.GetAllProjects();
        }

        private async void BindingData()
        {
            var temp = (ObservableCollection<ProjectInformationModel>)await ProjectRepository.Instance.GetAllProjects();
            var result = new ObservableCollection<ProjectInformationModel>();
            if (temp != null)
            {
                foreach (var p in temp)
                {
                    var members = await ProjectMemberRepository.Instance.GetAllProjectsMember(p.ID);
                    if (members != null)
                    {
                        var me = members.FirstOrDefault(t => t.UserID == GlobalData.MyUserID);
                        if (me != null && me.IsConfirmed != false)
                        {
                            result.Add(p);
                        }
                    }
                }
            }

            Projects = result;

            if (Projects == null)
            {
                return;
            }

            foreach (var projectInformationModel in Projects)
            {
                var projectTask = await TaskRepository.Instance.GetAllTasksForProject(projectInformationModel.ID);

                if (projectTask != null)
                {
                    projectInformationModel.NumberOfTask = projectTask.Count;
                }
            }

        }
    }
}
